package main
import (
    "flag"
    "fmt"
    "net"
    "net/http"
//    "net/http/httputil"
//    "net/url"
)
var (
    // 默认端口 用 -p
    dirPath = flag.String("d", "./", "根目录")
    // 默认文件地址是当前文件夹 用 -d
    port = flag.Int("p", 8080, "端口")
    // 默认反向代理 用 -porxy
//    proxy = flag.String("proxy", "", "反向代理")
)
func main() {

    flag.Parse()

    http.Handle("/",http.FileServer(http.Dir(*dirPath)))
    addProxy()
    fmt.Println("正在启动服好务:", *port)
    printIp()
    startServer(*port, nil)

}
// 启动
func startServer (port int, handler http.Handler) {
    fmt.Println("正在尝试端口:", port)
    err := http.ListenAndServe(fmt.Sprintf(":%d",port), handler)
    if err != nil {
        if port >= 9999 {
            fmt.Println("暂无可以端口,启动失败")
            return
        }
        // 递归自动向上找端口
        startServer(port+1, handler)
    }
}
// 打印ip
func printIp (){
    interfaces, err := net.Interfaces()
    if err != nil {
        err = fmt.Errorf("listing net interfaces: %w", err)
        return
    }
    for _, i := range interfaces {
        var addrs []net.Addr
        addrs, err = i.Addrs()
        if err != nil {
            err = fmt.Errorf("i.Addrs: %w", err)
            return
        }
        for _, addr := range addrs {
            var ip net.IP
            switch v := addr.(type) {
            case *net.IPNet:
                ip = v.IP
                case *net.IPAddr:
                    ip = v.IP
            }
            sip := fmt.Sprintf("%s",ip)
            if sip[0] == "1"[0] {
                fmt.Printf("listening on: http://%s:%d\n", ip, *port)
            }
        }
    }
}

/*
func addProxy(){
    // 如果有代理就启用
    if len(*proxy) != 0 {
        http.HandleFunc("/proxy", func (w http.ResponseWriter, r *http.Request){
            r.URL.Path = "" // 这句加上生效，我也不知道为怎么试出来的
            url, err := url.Parse(*proxy)
            if err != nil {
                fmt.Println(err)
                return
            }
            proxy := httputil.NewSingleHostReverseProxy(url)
            proxy.ServeHTTP(w, r)
        })
    }
}*/
